package com.lzdongrui.framework.web.service;

import com.lzdongrui.common.core.domain.entity.ClientUser;
import com.lzdongrui.common.core.domain.model.ClientLoginUser;
import com.lzdongrui.common.enums.UserStatus;
import com.lzdongrui.common.exception.ServiceException;
import com.lzdongrui.common.utils.StringUtils;
import com.lzdongrui.system.service.IClientUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("clientUserDetailsService")
public class ClientUserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(ClientUserDetailsServiceImpl.class);

    @Autowired
    private IClientUserService iClientUserService;

    @Autowired
    private ClientPasswordService clientPasswordService;

    @Autowired
    private ClientPermissionService clientPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ClientUser user=iClientUserService.selectUserBySno(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        if (user.getIsAtSchool()==2){
            log.info("学号：{} 的学生已毕业,无法进入系统！", username);
            throw new ServiceException("学号" + username + "的学生已毕业,无法进入系统！");
        }
        clientPasswordService.validate(user);
        return createClientLoginUser(user);
    }

    public UserDetails createClientLoginUser(ClientUser user){
        return  new ClientLoginUser(user.getId(),user,clientPermissionService.getMenuPermission(user));
    }
}
